import socket

def receive_messages(host='localhost', port=8889):
    """
    接收 TCP 服务端发送的消息
    :param host: 服务端主机地址
    :param port: 服务端端口号
    """
    # 创建 TCP 套接字
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        # 连接到服务端
        client_socket.connect((host, port))
        print("【√】已连接到 TCP 服务端.")
        while True:
            # 接收服务端发送的数据
            data = client_socket.recv(1024)
            if not data:
                # 若没有数据，说明连接已关闭
                break
            # 解码接收到的数据
            message = data.decode('utf-8')
            print(f"【√】接收到消息: {message}")
    except Exception as e:
        print(f"【X】发生错误: {e}")
    finally:
        # 关闭套接字
        client_socket.close()
        print("【√】TCP 连接已关闭.")

if __name__ == "__main__":
    receive_messages()